﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace SmartVault.Net
{
    /// <summary>
    /// MediaType
    /// 
    /// Per RFC 2616, http://www.w3.org/Protocols/rfc2616
    /// HTTP uses Internet Media Types [17]  in the Content-Type (section 14.17) and Accept (section 14.1) header fields in order to provide open and extensible data typing and type negotiation.
    /// </summary>
    public class MediaType
    {
        public MimeTypes Type { get; private set; }
        public Decimal Quality { get; private set; }
        private Dictionary<string, string> _parameters;

        public MediaType(MimeTypes type)
            : this(type, new Dictionary<string, string>())
        {
            

        }

        public MediaType(MimeTypes type, Dictionary<string,string> parameters)
        {
            this.Type = type;
            this.Quality = 1.0m;
            _parameters = parameters;

            string value = string.Empty;

            if (TryGetParameter(Constants.QualityParameter, out value))
            {
                decimal quality = 1.0m;

                if (Decimal.TryParse(value, out quality) 
                    && quality >= 0 && quality <= 1.0m)
                {
                    this.Quality = quality;
                }
            }            
        }

        public MediaType(string data)
        {
            this.Quality = 1.0m;
            _parameters = new Dictionary<string, string>();
            data = data.Trim();
            string[] items = data.Split(';');
            
            this.Type = (MimeTypes)items[0];

            for (int i = 1; i < items.Length; ++i)
            {
                string[] qlty = items[i].Split('=');
                qlty[0] = qlty[0].Trim();
                qlty[1] = qlty[1].Trim();
                if (qlty[0] == Constants.QualityParameter)
                {                    
                    this.Quality = Decimal.Parse(qlty[1]);
                }

                _parameters.Add(qlty[0], qlty[1]);
            }
        }

        public static bool operator ==(MediaType lhs, MediaType rhs)
        {
            if (((object)lhs) == null) return ((object)rhs) == null;
            return lhs.Equals(rhs);
        }

        public static bool operator !=(MediaType lhs, MediaType rhs)
        {
            return !(lhs == rhs);
        }

        public static explicit operator MediaType(string type)
        {
            return new MediaType(type);
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            return obj.ToString().Equals(this.ToString());
        }

        public string this[string key]
        {
            get { return _parameters[key]; }   
        }

        public bool IsParameterDefined(string key)
        {
            return _parameters.ContainsKey(key);
        }

        public bool TryGetParameter(string key, out string value)
        {
            return _parameters.TryGetValue(key, out value);
        }

        public override string ToString()
        {
            StringBuilder bld = new StringBuilder();
            bld.Append(this.Type);

            foreach (KeyValuePair<string,string> kv in _parameters)
            {
                bld.AppendFormat(" ;{0}={1}", kv.Key, kv.Value);
            }

            return bld.ToString();
        }
    }
}
